export default class GameControler {
    constructor(parent) {
        this.size = '40vw';
        this.keySize = '14vw';
        this.backgroundImage = './assets/control-panel.png';
        this.keyImage = './assets/control-key.png';
        this.isDrag = false;
        this.currentRadiuns = 0;
        this.currentAngle = 0;
        let mainPanle = document.createElement('div');
        mainPanle.style.width = this.size;
        mainPanle.style.height = this.size;
        mainPanle.style.backgroundImage = `url(${this.backgroundImage})`;
        mainPanle.style.backgroundSize = 'contain';
        mainPanle.style.position = 'fixed';
        mainPanle.style.bottom = '0';
        mainPanle.style.left = '0';
        parent.appendChild(mainPanle);
        let key = document.createElement('div');
        key.style.width = this.keySize;
        key.style.height = this.keySize;
        key.style.backgroundImage = `url(${this.keyImage})`;
        key.style.backgroundSize = 'contain';
        key.style.position = 'absolute';
        key.style.bottom = this.relPos;
        key.style.left = this.relPos;
        mainPanle.appendChild(key);
        this.regEvent(mainPanle, key);
    }
    get relPos() {
        return parseInt(this.size) / 2 - parseInt(this.keySize) / 2 + 'vw';
    }
    regEvent(panle, key) {
        let cx = panle.offsetLeft + panle.clientWidth / 2;
        let cy = panle.offsetTop + panle.clientHeight / 2;
        let max = panle.clientWidth / 2;
        key.addEventListener('touchstart', e => {
            this.isDrag = true;
        });
        panle.addEventListener('touchmove', e => {
            if (!this.isDrag)
                return;
            let { pageX: x, pageY: y } = e.touches[0];
            let tx = x - cx, ty = y - cy;
            let radius = Math.pow((Math.pow(tx, 2) + Math.pow(ty, 2)), 0.5);
            if (radius <= max) {
                key.style.left = x - panle.offsetLeft - key.offsetWidth / 2 + 'px';
                key.style.top = y - panle.offsetTop - key.offsetHeight / 2 + 'px';
            }
            else {
                let ax = (max * tx) / radius;
                let ay = (max * ty) / radius;
                key.style.left = ax + max - key.offsetWidth / 2 + 'px';
                key.style.top = ay + max - key.offsetWidth / 2 + 'px  ';
            }
            let radiuns = Math.atan2(ty, tx);
            let angle = (radiuns * 180 / Math.PI + 360) % 360;
            this.currentRadiuns = radiuns;
            this.currentAngle = angle;
        });
        panle.addEventListener('touchend', e => {
            this.isDrag = false;
            key.style.left = this.relPos;
            key.style.top = this.relPos;
        });
    }
}
